<template>
  <div class='search-container'>
    <!-- 搜索栏 -->
    <form action="/" class="search-form">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" background="#3296FA"
        @search="onSearch" @cancel="onCancel" @focus="searchResult = false" />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="searchResult" :searchText="searchText" />
    <!-- 搜索建议 -->
    <search-suggest v-else-if="searchText" :searchText="searchText" @link-search="onSearch" />
    <!-- 搜索历史 -->
    <search-history v-else :search-histories="searchHistories" @all-delete="allDelete" @search-text="searchContent"/>
  </div>
</template>
<script>
import searchHistory from './components/search-history.vue';
import searchSuggest from './components/search-suggest.vue';
import searchResult from './components/search-result.vue';
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchPage',
  components: {
    searchHistory,
    searchSuggest,
    searchResult,
  },
  props: {},
  data() {
    return {
      searchText: '', // 搜索栏内容
      searchResult: false, // 是否展示搜索结果
      searchHistories: getItem('TOUTIAO_HISTORY') || [], // 搜索历史记录
    };
  },
  created() {},
  computed: {},
  watch: {
    searchHistories() {
      setItem('TOUTIAO_HISTORY', this.searchHistories)
    }
  },
  methods: {
    searchContent(item) {
      this.searchText = item;
      this.searchResult = true
    },
    allDelete() {
      this.$dialog.confirm({
        title: '提示',
        message: '是否全部删除?',
      })
        .then(() => {
          // on confirm
          this.searchHistories = [];
        })
        .catch(() => {
          // on cancel
        });
    },
    onSearch(val) {
      console.log(val);
      this.searchText = val;
      // 判断搜索历史是否有重复的值
      let index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        // 如果有 去除该值
        this.searchHistories.splice(index, 1);
      }
      // 将值添加到头部
      this.searchHistories.unshift(val);
      this.searchResult = true;
    },
    onCancel() {
      this.$router.back();
    },
  },
};
</script>
<style lang='less' scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 1;
  }
}
</style>
